/**
 * PaginationTest This JavaScript file is for Canvas view.
 */

// maintain a count
var count = 0;
var showAlert = false; // control to enable or disable the alert boxes
var start = 0;
var limit = 2;
var page = 1;
var arrFriends = []; // array of friends to be invited
var viewerName = ''; // name of viewer

function init() {
    try {
        // Note: seek here for init() errors
        fetchPeople(page);

        var listOptions = '<select id="pagesize" onchange="showMessage(pagesize.value);limit=pagesize.value;page=1;fetchPeople(page);"> ';
        listOptions += ' <option value="2">2</option> ';
        listOptions += ' <option value="5">5</option> ';
        listOptions += ' <option value="10">10</option>';
        listOptions += ' <option value="25">25</option></select>';
        document.getElementById("ddlist").innerHTML = listOptions;

        /// test error handler
        handleException("testing error handler");
    } catch (err) {
        handleException("[init()] :" + err.description);
    }

}

// TODO: Write the code for Canvas view.

function fetchPeople(nPage) {
    try {
        // Note: seek here for fetchPeople() errors
        // calculate start # based on page number passed.
        var myStart = parseInt((nPage - 1) * limit, 10);
        var req = opensocial.newDataRequest();
        req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
        // id specification
        var params = {};
        params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;
        params[opensocial.IdSpec.Field.GROUP_ID] = 'FRIENDS';
        var idSpec = opensocial.newIdSpec(params);
        // options
        var opt_param = {};
        opt_param[opensocial.DataRequest.PeopleRequestFields.FIRST] = myStart;
        opt_param[opensocial.DataRequest.PeopleRequestFields.MAX] = limit;
        req.add(req.newFetchPeopleRequest(idSpec, opt_param), 'friends');
        // send request with an handler
        req.send(onLoadResponse);
    } catch (err) {
        handleException("[fetchPeople()] :" + err.description);
    }
}

function onLoadResponse(data) {
    try {
        // seek here for .*[friendsHTML].* errors
        // get viewer object
        var viewer = data.get('viewer').getData();
        // show viewer name
        viewerName = viewer.getDisplayName();
        document.getElementById("viewer").innerHTML = 'Hello, ' + viewerName + ', your friends are,';
        // get friends data
        var friends = data.get('friends').getData();
        document.getElementById("friends").innerHTML = '';

        var pageControls = '';
        var localcount = 0;
        var inviteControls = '';

        var friends_html = '';

        friends_html += '<table border="0" cellpadding="1" cellspacing="1" width="100%">';
        friends.each(function (person) {
            // / maintain a local count to decide
            localcount++;
            var name = person.getDisplayName();
            var id = person.getId();
            var profilePage = person.getField(opensocial.Person.Field.PROFILE_URL);
            var profileThumbnail = person.getField(opensocial.Person.Field.THUMBNAIL_URL);

            var friendDetails = "";
            friendDetails += "<tr width=\"100%\">";
            friendDetails += "<td align=\"left\" valign=\"center\" bgcolor=\"#fefefe\"> " + "<input type=\"checkbox\" name=\"chk" + localcount + "\" value=\"" + id + "\" onClick=\"updateSelection(this)\">" + name + "</input> <td> ";

            friendDetails += "</tr>";

            friends_html += friendDetails;

        });
        friends_html = friends_html + '</table>';
    } catch (err) {
        handleException("[onLoadResponse()] [friendsHTML]:" + err.description);
    }
    try {
        // Note: seek here for pageControls errors
        pageControls = '';
        if (page != 1) {
            // show back button only when start != 0
            pageControls += '<input type=\'button\' class=\'btn\' onClick=\'page=page-1;fetchPeople(page);\' value=\'<\' /> ';
        } else {
            pageControls += '<input type=\'button\' class=\'btn\' disabled value=\'<\' /> ';
        }

        pageControls += 'Page [' + page + ']  ';

        if (localcount == limit) {
            // if count matches, show next control
            // Problem: may show an extra button when pagination is exact
            pageControls += '<input type=\'button\' class=\'btn\' onClick=\'page=page+1;fetchPeople(page);\' value=\'>\' /> ';
        } else {
            pageControls += '<input type=\'button\' class=\'btn\' disabled value=\'>\' /> ';
        }

        inviteControls = '<input type="button" onClick="showMessage(arrFriends.toSource());" value="Show Selection" />';
        inviteControls += '<input type="button" onClick="inviteAll()" value="Invite" />';

    } catch (err) {
        handleException("[onLoadResponse()] [pageControls]:" + err.description);
    }

    try {
        // / Note: seek here for .*[innerHTML].* exceptions
        document.getElementById("pageCtrl").innerHTML = pageControls;
        document.getElementById("friends").innerHTML = friends_html;
        document.getElementById("friends").innerHTML += inviteControls;
    } catch (err) {
        handleException("[onLoadResponse()] [innerHTML]:" + err.description);
    }
    gadgets.window.adjustHeight();
}

function updateSelection(checkBox) {
    try {
        if (checkBox.checked) {
            showMessage(checkBox.value + ' will be added');
            // add it into array
            arrFriends.push(checkBox.value);
        } else {
            showMessage(checkBox.value + ' will be REMOVED');
            // remove that from friends
            var index = arrFriends.indexOf(checkBox.value);
            if (index != -1) {
                arrFriends.splice(index, 1);
            }
        }
    } catch (err) {
        handleException("[updateSelection()] :" + err.description);
    }

}

function inviteAll() {
    showMessage("invitation sending to: " + arrFriends);
    try {
        var reason_body = viewerName + " is inviting you to use the FriendInvite Applciation!";
        var reason_message = opensocial.newMessage(reason_body);
        // send invitation, result will be dealt in inviteDone function
        opensocial.requestShareApp(
        arrFriends, reason_message, function inviteDone(return_data) {
            if (return_data.hadError() === false) {
                showMessage("your Invitations has been sent! congratulations!");
            } else {
                showMessage(" :( error message: " + return_data.getErrorCode());
            }
        });
    } catch (err) {
        handleException("[inviteAll()] :" + err.description);
    }
}

// / this function will append current error text to error section
// / err = string object


function handleException(err) {
    if (showAlert) {
        alert(err);
    }
    document.getElementById("errors").innerHTML += err;
}

// / this function will show alert message based on settings
// / else bypass it.
// / err = string object


function showMessage(err) {
    if (showAlert) {
        alert(err);
    }
}